package com.ibuonline.b2b.common;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.dimeng.common.util.SystemConfig;

public class CacheUtil {
	private static List<String> servers = null;
	private static CacheUtil instance = new CacheUtil();
	private static Random rnd = new Random();
	
	private CacheUtil() {
		String[] arr = SystemConfig.getProperty("app.servers",
				"192.168.0.242:8080;192.168.0.243:8080").split("[;, ]");
		servers = new ArrayList<String>();
		for (String server : arr) {
			if (server.trim().equals("")) continue;
			servers.add(server.trim());
		}
	}
	
	public static CacheUtil getInstance() {
		return instance;
	}
	
	public void flushPage(String key) {
		flushPage(key, "false");
	}
	
	public void flushPage(String key, String pattern) {
		for (String server : servers) {
			try {
				URL url = new URL("http://"+server + "/flushOSCache.do?key=" + key + 
						("true".equals(pattern) ? "&pattern=true" : "") + "&t="+rnd.nextInt(1000));
				URLConnection URLConn = (HttpURLConnection) url.openConnection();
				InputStream ins = URLConn.getInputStream();
				ins.close();
			} catch(Exception e) {
				System.out.println(e);
			}
		}
	}
	
	public void flushShop(Integer companyId) {
		String loginName = SysCache.getLoginNameByCompanyId(companyId);
		if (loginName != null) 
			flushGoldShop(loginName);
		else flushFreeShop(companyId);
	}

	public void flushGoldShop(String loginName) {
		for (String server : servers) {
			try {
				URL url = new URL("http://"+server + "/flushGoldShop.do?loginName=" + 
						loginName + "&t="+rnd.nextInt(1000));
				URLConnection URLConn = (HttpURLConnection) url.openConnection();
				InputStream ins = URLConn.getInputStream();
				ins.close();
			} catch(Exception e) {
				System.out.println(e);
			}
		}
	}
		
	public void flushFreeShop(Integer companyId) {
		for (String server : servers) {
			try {
				URL url = new URL("http://"+server + "/flushFreeShop.do?companyId=" + 
						companyId + "&t="+rnd.nextInt(1000));
				URLConnection URLConn = (HttpURLConnection) url.openConnection();
				InputStream ins = URLConn.getInputStream();
				ins.close();
			} catch(Exception e) {
				System.out.println(e);
			}
		}
	}
}
